<script setup>
import { ArrowLeftIcon } from 'tdesign-icons-vue-next'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MainContent from '@/components/Main-Content.vue'
import { addCompanyItem, editCompanyItem, getCompanyItem, getIndustryList } from '@/api/company'
import { getToken } from '@/utils/storage'
import { MessagePlugin } from 'tdesign-vue-next'

const router = useRouter()
const route = useRoute()
const requestHeaders = {
    Authorization: 'Bearer ' + getToken()
}
const form = ref({})
const rules = ref({
    name: [
        { required: true, message: '请输入企业名称', trigger: 'blur' }
    ],
    registeredAddress: [
        { required: true, message: '请输入注册地址', trigger: 'blur' }
    ],
    legalPerson: [
        { required: true, message: '请输入法人姓名', trigger: 'blur' }
    ],
    industryCode: [
        { required: true, message: '请选择所在行业', trigger: 'change' }
    ],
    businessLicenseUrl: [
        { required: true, message: '请上传营业执照', trigger: 'change' }
    ],
    contact: [
        { required: true, message: '请输入联系人员', trigger: 'blur' }
    ],
    contactNumber: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur' }
    ]
})
const industryList = ref([])
const fileList = ref([])
const formInstance = ref(null)

if (route.query.type === 'edit') {
    getCompanyItem(route.query.id).then(res => {
        fileList.value = [{ name: res.data.businessLicenseName }]
        form.value = res.data
    })
}

const back = () => router.back()
const getIndustry = async () => {
    industryList.value = (await getIndustryList()).data
}
const reset = () => {
    fileList.value = []
    formInstance.value.reset()
}
const uploadSuccess = ({ response: { data } }) => {
    const params = {
        businessLicenseId: data.id,
        businessLicenseUrl: data.url
    }
    form.value = { ...form.value, ...params }
}
const confirm = async () => {
    const valid = await formInstance.value.validate()
    if (typeof valid === 'boolean' && valid) {
        if (route.query.type === 'add') {
            const res = await addCompanyItem(form.value)
            if (res.code !== 10000) return
            reset()
            await MessagePlugin.success('添加成功！')
        } else {
            const params = form.value
            delete params.businessLicenseName
            delete params.industryName
            delete params.rent
            const res = await editCompanyItem(form.value)
            if (res.code !== 10000) return
            fileList.value = []
            form.value.businessLicenseUrl = ''
            await MessagePlugin.success('修改成功！')
        }
    }
}

getIndustry()
</script>

<template>
    <main-content>
        <div class="header">
            <t-button variant="outline" @click="back">
                <template #icon>
                    <ArrowLeftIcon/>
                </template>
                返回
            </t-button>
            <span class="title">{{ route.query.type === 'edit' ? '编辑企业' : '新增企业' }}</span>
        </div>

        <t-divider theme="vertical"/>

        <div class="body">
            <t-form ref="formInstance" labelAlign="top"
                    :rules="rules" :data="form">
                <t-card title="企业信息" header-bordered style="margin-right: 20px;">
                    <t-form-item label="企业名称" name="name">
                        <t-input v-model.trim="form.name" placeholder="请输入企业名称"></t-input>
                    </t-form-item>
                    <t-form-item label="注册地址" name="registeredAddress">
                        <t-input v-model.trim="form.registeredAddress" placeholder="请输入注册地址"></t-input>
                    </t-form-item>
                    <t-form-item label="法人姓名" name="legalPerson">
                        <t-input v-model.trim="form.legalPerson" placeholder="请输入法人姓名"></t-input>
                    </t-form-item>
                    <t-form-item label="所在行业" name="industryCode">
                        <t-select
                            filterable
                            placeholder="请选择所在行业"
                            v-model.trim="form.industryCode"
                            showArrow>
                            <t-option v-for="e in industryList" :value="e.industryCode" :key="e.industryCode"
                                      :label="e.industryName"/>
                        </t-select>
                    </t-form-item>
                    <t-form-item label="营业执照" name="businessLicenseUrl">
                        <t-upload action="https://api-hmzs.itheima.net/api/upload"
                                  :triggerButtonProps="{ theme: 'primary', variant: 'outline' }"
                                  accept=".jpg, .jpeg, .png" :headers="requestHeaders" :data="{type: 'businessLicense'}"
                                  @success="uploadSuccess" v-model:files="fileList" :defaultFiles="fileList"
                                  placeholder="支持扩展名：.jpg .jpeg .png, 文件大小不得超过5M"/>
                    </t-form-item>
                </t-card>

                <t-card title="联系人信息" header-bordered>
                    <t-form-item label="联系人员" name="contact">
                        <t-input v-model.trim="form.contact" placeholder="请输入联系人员"></t-input>
                    </t-form-item>
                    <t-form-item label="联系电话" name="contactNumber">
                        <t-input v-model.trim="form.contactNumber" placeholder="请输入联系电话"></t-input>
                    </t-form-item>
                </t-card>
            </t-form>
        </div>
        <div class="bottom">
            <div>
                <t-button variant="outline" @click="reset">重 置</t-button>
                <t-button style="margin-left: 20px" @click="confirm">确 定</t-button>
            </div>
        </div>
    </main-content>
</template>

<style scoped lang="scss">
.header {
    display: flex;
    align-items: center;
    padding: 20px 20px 0;

    .title {
        color: var(--td-text-color-primary);
        font-size: 24px;
        font-weight: 600;
        margin-left: 30px;
    }
}

.t-form {
    padding: 10px 30px;
    display: flex;

    .t-card {
        width: 100%;
    }
}

.bottom {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding-top: 20px;
}

.t-divider {
    margin: 20px 0;
}
</style>
